import { getToken, setToken, removeToken,getUserMsg,setUserMsg,removeUserMsg, } from '@/utils/auth'
import { login,getPersonMsg } from '@/api/user'
import {constantRoutes} from '@/router/index'
import {resetRouter} from '@/router/index'
const state = {
  token: getToken(),
  userInfo:getUserMsg(),
  routes:constantRoutes
}

const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  removeUserMsg(state) {
    state.userInfo={}
    
    removeUserMsg()
  },
  async setUserMessage(state,user) {
    state.userInfo=user
    setUserMsg(user)
  },
  setRoutes(state,newRoutes) {
    state.routes=[...constantRoutes,...newRoutes]  // 静态路由+动态路由
  }
}

const actions = {
  // 设置token
  async login(context, data) {
    const result = await login(data)
    context.commit('setToken', result)
    
  },
  // 个人信息
  async userMsg(context,data) {
    const result=await getPersonMsg()
    context.commit('setUserMessage',result)
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserMsg')
    // 退出登录 重置路由
    resetRouter()
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
